<?php

namespace Addons\OaSystem\Controller;
use Think\ManageBaseController;

class OaWorkTimeSettingController extends OaBaseController
{
    var $model;

    function _initialize()
    {
        $this->model = $this->getModel('oa_work_time_setting');

        parent::_initialize();
        $controller = strtolower(CONTROLLER_NAME);
        $action = strtolower(ACTION_NAME);

        $res ['title'] = '考勤信息';
        $res ['url'] = addons_url('OaSystem://OaEmpAttendance/attendancelists', array('mdm' => I('mdm')));
        $res ['class'] = $action == 'attendancelists' ? 'cur' : '';
        $nav [] = $res;
        $this->assign('nav', $nav);

        $res ['title'] = '考勤列表';
        $sub_nav[] = $res;
        $res ['title'] = '加班列表';
        $res ['url'] = addons_url('OaSystem://OaEmpAttendance/overtimelists', array('mdm' => I('mdm')));
        $res ['class'] = $action == 'overtimelists' ? 'cur' : '';
        $sub_nav[] = $res;
        $res ['title'] = '请假列表';
        $res ['url'] = addons_url('OaSystem://OaEmpAttendance/leavelists', array('mdm' => I('mdm')));
        $res ['class'] = $action == 'leavelists' ? 'cur' : '';
        $sub_nav[] = $res;
        $res ['title'] = '考勤点管理';
        $res ['url'] = addons_url('OaSystem://OaCheckPoint/lists', array('mdm' => I('mdm')));
        $res ['class'] = $controller == 'oacheckpoint' ? 'cur' : '';
        $sub_nav[] = $res;
        $res ['title'] = '工作时间设置';
        $res ['url'] = addons_url('OaSystem://OaWorkTimeSetting/lists', array('mdm' => I('mdm')));
        $res ['class'] = $controller == 'oaworktimesetting' ? 'cur' : '';
        $sub_nav[] = $res;
        $this->assign('sub_nav', $sub_nav);
    }

    function lists()
    {
        $res['title'] = 'excel录入';
        $res['is_buttion'] = false;
        $res['url'] = addons_url('OaSystem://OaWorkTimeSetting/import', array('mdm' => I('mdm')));
        $top_more_button[] = $res;

        $this->assign('top_more_button', $top_more_button);
        $this->assign('add_button', true);

        $list_data = $this->_get_model_list($this->model);
        $grids = $list_data['list_grids'];
        $data = $list_data['list_data'];

        foreach ($data as $i => $v) {
            $tmpstr = null;
            $clockon = json_decode($v['clockon'], true);
            foreach ($clockon as $c) {
                $tmpstr .= ((int)($c/3600)).':'.sprintf("%02d", ($c/60)%60).' ';
            }
            $data[$i]['clockon'] = $tmpstr;
            $data[$i]['legal_holidays'] = $this->convDateTsListToStr($v['legal_holidays']);
            $data[$i]['adjust_rest_days'] = $this->convDateTsListToStr($v['adjust_rest_days']);
            $data[$i]['adjust_work_days'] = $this->convDateTsListToStr($v['adjust_work_days']);
        }

        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function import()
    {

        if (IS_POST) {
            $data['file'] = I('post.worktime');
            $data['valid_date'] = date('y-m-d h:i:s', time());

            if (!intval($data['file'])) $this->error("数据文件未上传！");

            //这里是要用一个单独的表（模型）对导入行为进行记录！
            //$import_model = D('WxyClassCourseimport');
            //$import_model->add($data);

            if ($this->import_worktime_data_from_excel($data['file'], $data['valid_date'], $data['comment'])) {
                $this->success('保存成功！', U('lists'/*'import?model=' . $this->model ['name'], $this->get_param */), 600);
            }
        } else {
            $res['title'] = '工作时间安排表';
            $res['is_must'] = true;
            $res['is_show'] = 1;
            $res['name'] = 'worktime';
            $res['type'] = 'file';
            $fields[] = $res;
            $post_url = addons_url('OaSystem://OaWorkTimeSetting/import');
            $this->assign('fields', $fields);
            $this->assign('post_url', $post_url);
            $this->assign('import_template', 'template_worktime.xlsx');
            $this->display();
        }
    }

    private function import_worktime_data_from_excel($file_id, $date = NULL, $comment = NULL) {
        if ($date == NULL) return false;
        $data = array();
        $column = array (
            'A'=>'year', //年号
            'B'=>'clockon',  //规定打卡时间
            'C'=>'legal_holidays',  //法定节假日
            'D'=>'adjust_rest_days',  //调整休息日
            'E'=>'adjust_work_days',      //调整上班日
        );

        $data = importFormExcel($file_id, $column);
        if ($data['status']) {
            foreach  ($data['data'] as $row) {
                $row['appid'] = $this->appId;

                $row['clockon'] = $this->convClockonListToTs($row['clockon']);
                $row['legal_holidays'] = $this->convDateStrListToTs($row['legal_holidays']);
                $row['adjust_rest_days'] = $this->convDateStrListToTs($row['adjust_rest_days']);
                $row['adjust_work_days'] = $this->convDateStrListToTs($row['adjust_work_days']);
                foreach ($row as $v) {
                    if(empty($v)) {
                        $this->error('导入excel的时间日期格式有错，请检查！');
                        return false;
                    }
                }
                if(db_find('oa_work_time_setting', ['year'=>$row['year']])) {
                    $this->error('该年号的表已经导入，如需修改，请先删除再导入,谢谢！');
                    return false;
                }
                M('oa_work_time_setting')->add($row);
            }
            return true;
        }
        else {
            $this->error('请检查文件格式');
            return false;
        }

    }
    private function convClockonListToTs($clockonList) {
        $clockon_arr = explode(';', $clockonList);
        $clockon_ts = array();
        $clockZeroTs = strtotime('00:00');
        foreach ($clockon_arr as $i => $v) {
            if(empty($v))
                continue;
            if(($tmpTs = strtotime($v))==false)
                return false;
            array_push($clockon_ts, $tmpTs-$clockZeroTs);
        }
        if((count($clockon_ts) == 0) || (count($clockon_ts)%2 == 1)) {
            $this->error('得到的打卡时间数量不对，请检查，请注意分号不能是中文输入法的分号。');
            return false;
        }

        return json_encode($clockon_ts);
    }

    private function convDateStrListToTs($dateStrList) {
        if(empty($dateStrList)) {
            $this->error(__METHOD__.'['.__LINE__.']'.'传入的$dateStrList为空！');
            return false;
        }

        $string_arr = explode(';', $dateStrList);
        $timestamp_arr = array();
        foreach ($string_arr as $v) {
            if(empty($v))
                continue;
            if(($tmpTs = strtotime($v))==false)
                return false;
            array_push($timestamp_arr, $tmpTs);
        }
        return json_encode($timestamp_arr);
    }

    private function convDateTsListToStr($dateTimeList) {
        if(empty($dateTimeList)) {
            $this->error(__METHOD__.'['.__LINE__.']'.'传入的$dateTimeList为空！');
            return false;
        }
        $timestamp_arr = json_decode($dateTimeList, true);
        $date_string = null;
        foreach ($timestamp_arr as $v) {
            $date_string .= date('Y-m-d', $v);
            $date_string .= ';';
            $date_string .= '<br>';
        }
        return $date_string;
    }
}